<?php

namespace app\admin\model\scanwork;

use think\Model;

class Product extends Model
{
    // 表名
    protected $name = 'scanwork_product';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];
    
    public function getStatusList()
    {
        return ['0' => __('禁用'), '1' => __('正常')];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    // 获取产品编码
    public function getProductCodeAttr($value, $data)
    {
        if (empty($value) && isset($data['id'])) {
            $value = 'PD-' . date('Y') . '-' . str_pad($data['id'], 3, '0', STR_PAD_LEFT);
        }
        return $value;
    }

    // 检查产品编码是否唯一
    public function checkCodeUnique($code, $id = null)
    {
        $where = ['product_code' => $code];
        if ($id) {
            $where['id'] = ['<>', $id];
        }
        return $this->where($where)->count() == 0;
    }

    // 获取产品工艺路线
    public function getProcessRouteAttr($value, $data)
    {
        if (is_string($value)) {
            return json_decode($value, true) ?: [];
        }
        return $value ?: [];
    }

    // 设置产品工艺路线
    public function setProcessRouteAttr($value, $data)
    {
        if (is_array($value)) {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 获取质量标准
    public function getQualityStandardsAttr($value, $data)
    {
        if (is_string($value)) {
            return json_decode($value, true) ?: [];
        }
        return $value ?: [];
    }

    // 设置质量标准
    public function setQualityStandardsAttr($value, $data)
    {
        if (is_array($value)) {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 获取产品图片
    public function getProductImagesAttr($value, $data)
    {
        if (is_string($value)) {
            return json_decode($value, true) ?: [];
        }
        return $value ?: [];
    }

    // 设置产品图片
    public function setProductImagesAttr($value, $data)
    {
        if (is_array($value)) {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 获取参考图片
    public function getReferenceImagesAttr($value, $data)
    {
        if (is_string($value)) {
            return json_decode($value, true) ?: [];
        }
        return $value ?: [];
    }

    // 设置参考图片
    public function setReferenceImagesAttr($value, $data)
    {
        if (is_array($value)) {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        return $value;
    }

    // 关联型号
    public function models()
    {
        return $this->hasMany('ProductModel', 'product_id', 'id');
    }

    // 关联订单
    public function orders()
    {
        return $this->hasManyThrough('Order', 'ProductModel', 'product_id', 'model_id', 'id', 'id');
    }

    // 关联溯源记录
    public function traceabilities()
    {
        return $this->hasMany('Traceability', 'product_id', 'id');
    }

    // 获取产品统计信息
    public function getProductStats()
    {
        $orderCount = $this->orders()->count();
        $totalQuantity = $this->orders()->sum('total_quantity');
        $modelCount = $this->models()->count();
        $traceabilityCount = $this->traceabilities()->count();
        
        return [
            'order_count' => $orderCount,
            'total_quantity' => $totalQuantity,
            'model_count' => $modelCount,
            'traceability_count' => $traceabilityCount
        ];
    }

    // 生成默认工艺路线
    public function generateDefaultProcessRoute()
    {
        $processes = \app\admin\model\scanwork\Process::where('status', 1)
            ->order('id')
            ->column('name');
        
        return $processes;
    }

    // 验证工艺路线
    public function validateProcessRoute($processRoute)
    {
        if (empty($processRoute)) {
            return true;
        }
        
        $processNames = \app\admin\model\scanwork\Process::where('status', 1)
            ->column('name');
        
        foreach ($processRoute as $processName) {
            if (!in_array($processName, $processNames)) {
                return false;
            }
        }
        
        return true;
    }
} 